﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Web.AdminMvc.Models;
using ApplicationCore.Entities;
using ApplicationCore.Interfaces;
using ApplicationCore.Services;
using ApplicationCore.Specifications;
using Infrastructure;

namespace Web.AdminMvc.Controllers
{
    public class RoomController : Controller
    {
		private readonly IRoomRepository _roomRepository;


		public RoomController(IRoomRepository  roomRepository) {
			_roomRepository = roomRepository;


		}

		#region 列表

		public IActionResult Index()
		{

			return View();
		}


		public JsonResult GetPageList(Pager pager)
		{

			var list = _roomRepository.ListAll().ToList().Select(s => new RoomViewModel(s)).ToList();

			return new TableViewModel
			{
				code = 0,
				count = list.Count,
				data = list.OrderBy(s => s.Id).Skip((pager.page - 1) * pager.limit).Take(pager.limit),
				msg = "",
			}.CreateJsonResult();

		}

		#endregion
		 

		#region cud
		public IActionResult Create(int id)
		{
			var model = _roomRepository.GetById(id);
			if (model == null) model = new Room();
			return View(model);
		}

		[HttpPost]
		public async Task<JsonResult> Create(Room model)
		{
			try
			{
				if (ModelState.IsValid)
				{
					if (model.Id > 0)
					{
						await	_roomRepository.AddAsync(model);
					}
					else
					{
						await _roomRepository.UpdateAsync(model);
					}
					
					return Json(AjaxExtensions.CreateSuccess());
				}
				else
				{
					return Json(AjaxExtensions.CreateFail("表单验证失败"));
				}
			}
			catch (Exception ex)
			{
				return Json(AjaxExtensions.CreateFail(ex));
			}
		}

		[HttpPost]
		public async Task<JsonResult> Del(int id) {
			var room = _roomRepository.GetById(id);

			await _roomRepository.DeleteAsync(room);

			return Json(AjaxExtensions.CreateSuccess());
		}
		#endregion

		public async Task<JsonResult> Stop(int id) {
			var room =await _roomRepository.GetByIdAsync(id);
			if(room.State==RoomState.Opened)
			room.State = RoomState.Shutdown;
			else
			{
				room.State = RoomState.Opened;

			}

			 await  _roomRepository.UpdateAsync(room);

			return Json(AjaxExtensions.CreateSuccess().SetData(room));
		}

		public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
